<template>
	<view class="p30">
		<u-navbar :title="title" back-icon-color="#333" title-color="#333" :title-bold="true">
		</u-navbar>
		<u-form label-width="120rpx" :label-style="{
			fontSize: '26rpx',
			fontFamily: 'PingFangSC-Medium, PingFangSC-Medium',
			fontWeight: '600',
			color: '#333333'
		}" :model="addressForm" ref="uForm" :error-type="['toast']">
			<view class="bdr20 bgcf p24" style="padding-top: 0;">
				<u-form-item class="noeFitem" label="收货人" prop="receiver">
					<u-input :disabled="addressForm.addressId" input-align="right" v-model="addressForm.receiver" placeholder="收货人姓名" />
					<!-- <view class="df" style="justify-content: flex-end;margin-right: -20rpx;">
						<u-radio-group label-size="26" active-color="#48A147" v-model="addressForm.sex">
							<u-radio name="1">
								<text class="fs26" :class="addressForm.sex == 1 ? 'c3' :'c9'">女士</text>
							</u-radio>
							<u-radio name="2">
								<text class="fs26" :class="addressForm.sex == 2 ? 'c3' :'c9'">先生</text>
							</u-radio>
						</u-radio-group>
					</view> -->
				</u-form-item>
				<u-form-item label="联系电话" prop="phone"><u-input :disabled="addressForm.addressId" input-align="right" placeholder="请输入联系电话"
						v-model="addressForm.phone" /></u-form-item>
				<u-form-item label="店铺名称" prop="shopName"><u-input :disabled="addressForm.addressId"  input-align="right" placeholder="请填写店铺名称"
						v-model="addressForm.shopName" /></u-form-item>
				<u-form-item  label="收货地址" prop="receiveAddress">
					<view class="df aic" style="justify-content: flex-end;">
						<u-input :disabled="addressForm.addressId" style="width: 500rpx;" @click="addressSelect" placeholder="小区名称/店铺名称等" input-align="right" disabled
							v-model="addressForm.receiveAddress" />
						<nmr-icon class="ml10" @click="addressSelect" name="xiangyou1" size="30" color="#666"></nmr-icon>
					</view>
				</u-form-item>

				<u-form-item label="所在地区"><u-input input-align="right" disabled placeholder="省，市，区"
						v-model="addressForm.areaAddress" /></u-form-item>
				<u-form-item label="门牌号" prop="homeNumber"><u-input :disabled="addressForm.addressId"  input-align="right" placeholder="楼号/门牌号"
						v-model="addressForm.homeNumber" /></u-form-item>
				<u-form-item label="门头照片">
					<view class="df jcsb w100" style="">
						<text></text>
						<u-upload :file-list="fileList" ref="uUpload" :action="uploadUrl" class="uUpload" max-count="1"
							style="border-radius: 50%;" width="75" height="75" :custom-btn="true">
							<view slot="addBtn" class="slot-btn" hover-class="slot-btn__hover" hover-stay-time="150">
								<nmr-icon name="zhaopian" size="35" color="#fff"></nmr-icon>
							</view>
						</u-upload>
					</view>
				</u-form-item>
				<u-form-item :border-bottom="false" label-width="200" label="设置为默认地址">
					<view class="df jcsb w100" style="">
						<text></text>
						<u-switch active-color="#48A147" size="30" inactive-color="#999999"
							v-model="addressForm.isDefault"></u-switch>
					</view>

				</u-form-item>
				<view class="c3 fs24 fw4">
					在下次购物时将优先选择该地址，避免下单时选择错误地址
				</view>

			</view>

			<view class="bdr20 bgcf p24 mt20">
				<view class="df aic jcsb">
					<view class="df aic">
						<text class="fs26 fw5 c3">信任签收</text>
						<view class="recommendLabel">
							推荐开启
						</view>
					</view>
					<u-switch active-color="#48A147" size="30" inactive-color="#999999"
						v-model="addressForm.isTrust"></u-switch>
				</view>
				<view class="p24 c3 fs24 fw4 bdr20 bgcf1 mt20">
					开启信任签收后，司机会将货品放于您指定的地点或店铺
					门口，无需当面交接。
				</view>
			</view>
			<view class="bdr20 bgcf  mt20" style="padding: 0 24rpx;">
				<u-form-item :border-bottom="false" label="放置点位置照片" label-width="200">
					<view class="df jcsb w100" style="">
						<text></text>
						<u-upload :file-list="fileListPlace" ref="placeImagesRef" :action="uploadUrl" class="pointUpload"
							max-count="1" width="140" height="140">
						</u-upload>
					</view>
				</u-form-item>
			</view>
			<view class="bdr20 bgcf mt20" style="padding: 0 24rpx;">
				<u-form-item :border-bottom="false" label="备注"><u-input input-align="right" placeholder="请输入备注"
						v-model="addressForm.remark" /></u-form-item>
			</view>
			<view class="footer df jcc">
				<u-button type="primary" shape='circle' @click="handlesubmit" :loading="loading"
					:custom-style="{fontSize: '30rpx', color: '#ffffff',width: '630rpx', height: '88rpx',background: 'linear-gradient(90deg, #48A147 0%, #8AE38A 100%);'}"
					ripple>保存收货地址</u-button>
			</view>
		</u-form>
		<view class="" style="height: 180rpx;">

		</view>
	</view>
</template>

<script>
	import QQMapWX from '@/common/qqmap-wx-jssdk.js'
	import {
		bMemberAddressAdd,
		bMemberAddressEdit,
		shopAccountDetail
	} from "@/api/address.js"
	export default {
		data() {
			return {
				title: '收货地址',
				customStyle: {
					background: 'linear-gradient(90deg, #48A147 0%, #8AE38A 100%);',
				},
				fileList: [],
				fileListPlace:[],
				addressForm: {
					receiver: '',
					phone: '',
					sex: '1',
					shopName: '',
					homeNumber: "",
					switchVal: true,
					receiveAddress: '',
					pcode: '',
					ccode: '',
					acode: '',
					area: '',
					isDefault: false,
					isTrust: false,
					remark: '',
					lat: '',
					lng: '',
					areaAddress:''
				},
				uploadUrl: this.APPUPLOAD,
				rules: {
					receiver: [{
						required: true,
						message: '请输入收货人',
						// 可以单个或者同时写两个触发验证方式 
						trigger: 'blur',
					}],
					receiveAddress: [{
						required: true,
						message: '请选择收货地址',
						trigger: ['change', 'blur']
					}],
					homeNumber: [{
						required: true,
						message: '请输入门牌号',
						trigger: 'blur',
					}],

					shopName: [{
						required: true,
						message: '请输入店铺名称',
						// 可以单个或者同时写两个触发验证方式 
						trigger: 'blur',
					}],
					phone: [{
						required: true,
						message: '请输入手机号码',
						trigger: ['change', 'blur']
					}, {
						// 自定义验证函数，见上说明
						validator: (rule, value, callback) => {
							if (value == "") {
								return true;
							} else {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								// this.$u.test.mobile()就是返回true或者false的
								return this.$u.test.mobile(value);
							}
						},
						message: '手机号码不正确',
						// 触发器可以同时用blur和change
						trigger: ['change', 'blur'],
					}],
				}
			}
		},
		onLoad(e) {
			if (e.type === 'update') {
				this.getInfo(e.addressId)
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules)
		},
		methods: {
			getInfo(addressId) {
				shopAccountDetail(addressId).then(res => {
					if (res.code === 200) {
						const data = res.data
						this.addressForm = data
						this.addressForm.isDefault = data.isDefault != 1
						this.addressForm.isTrust = data.isTrust != 1
						this.addressForm.areaAddress = data.province + data.city + data.area
						this.fileList = this.addressForm.homeImage.split(',').map(e =>{
							return {
								url: e
							}
						})
						this.fileListPlace = this.addressForm.placeImages.split(',').map(e =>{
							return {
								url: e
							}
						})
					} else {
						uni.showToast({
							title: res.message,
							icon: 'none'
						})
					}
				})
			},
			handlesubmit() {
				this.$refs.uForm.validate(valid => {
					if (valid) {
						let files = [];
						files = this.$refs.uUpload.lists.filter(val => {
							return val.progress == 100;
						})
						let bill = []
						if (files.length > 0) {
							files.forEach(v => {
								bill.push(v.response ? v.response.data.url : v.url)
							})
						}
						if (!files.length) {
							this.$u.toast('请上传门头照片！')
							return
						}
						let placeImages = [];
						placeImages = this.$refs.placeImagesRef.lists.filter(val => {
							return val.progress == 100;
						})
						let placeImagesList = []
						if (placeImages.length > 0) {
							placeImages.forEach(v => {
								placeImagesList.push(v.response ? v.response.data.url : v.url)
							})
						}
						if (!placeImages.length&&this.addressForm.isTrust) {
							this.$u.toast('请上传放置点位置照片！')
							return
						}
						this.addressForm.placeImages = placeImagesList.toString()
						this.addressForm.homeImage = bill.toString()
						const form = {
							...this.addressForm,
							isDefault: this.addressForm.isDefault ? 0 : 1,
							isTrust: this.addressForm.isTrust ? 0 : 1
						}
						if (this.addressForm.addressId) {
							bMemberAddressEdit(form).then(res => {
								if (res.code === 200) {
									uni.showToast({
										title: '编辑成功',
										icon: 'none'
									})
									uni.navigateBack()
								} else {
									uni.showToast({
										title: res.message,
										icon: 'none'
									})
								}
							})
						} else {
							bMemberAddressAdd(form).then(res => {
								if (res.code == 200) {
									uni.showToast({
										title: '添加成功',
										icon: 'none'
									})
									uni.navigateBack()
								} else {
									uni.showToast({
										title: res.msg,
										icon: 'none',
										mask: true
									})
								}
							})
						}
					} else {}
				})
			},
			addressSelect() {
				if(this.addressForm.addressId)return
				let that = this
				const qqmapsdk = new QQMapWX({
					key: this.$QQMapWXKey
				});
				uni.chooseLocation({
					success: function(res) {
						that.addressForm.receiveAddress = res.name
						that.addressForm.areaDetailAddress = res.address
						that.addressForm.lng = res.longitude
						that.addressForm.lat = res.latitude
						qqmapsdk.reverseGeocoder({
							location: {
								latitude: res.latitude,
								longitude: res.longitude
							},
							get_poi: 0,
							success: async (r) => {
								let {
									adcode,
									city_code,
									province,
									city,
									district
								} = r.result.ad_info
								try{
									that.addressForm.provinceId = adcode.slice(0, 2).padEnd(6, 0) //省
									that.addressForm.cityId = city_code.slice(3) //市
									that.addressForm.areaId = adcode //区
									that.addressForm.province = province //省
									that.addressForm.city = city //市
									that.addressForm.area = district //市
									that.addressForm.areaAddress = province + city + district //区
								}catch(e){
									console.log(e)
									//TODO handle the exception
								}

							},
							fail: (res) => {
								uni.showToast({
									title: '您已拒绝定位服务获取当前位置，请设置开启定位服务',
									icon: 'none'
								})
							}
						})
						// console.log('位置名称：' + res.name);
						// console.log('详细地址：' + res.address);
						// console.log('纬度：' + res.latitude);
						// console.log('经度：' + res.longitude);
					}
				});

			}
		}
	}
</script>

<style scoped lang="scss">
	.noeFitem /deep/ .u-form-item--left.data-v-006449ec {
		display: block !important;
	}

	.slot-btn {
		width: 75rpx;
		height: 75rpx;
		background: #E5732E;
		opacity: 1;
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 50%;
	}

	.slot-btn__hover {
		background-color: rgb(235, 236, 238);
	}

	.uUpload ::v-deep .u-preview-image {
		border-radius: 50% !important;
	}

	.uUpload ::v-deep .u-list-item {
		background: #fff !important;
	}

	.uUpload ::v-deep .u-preview-wrap {
		border: none !important;
	}

	.recommendLabel {
		padding: 8rpx 16rpx;
		background: linear-gradient(90deg, #48A147 0%, #8AE38A 100%);
		border-radius: 10rpx;
		font-size: 24rpx;
		font-family: PingFang SC, PingFang SC;
		font-weight: 400;
		color: #FFFFFF;
		margin-left: 20rpx;
	}

	.bgcf1 {
		background: #F1F1F1;
	}

	.footer {
		position: fixed;
		height: 150rpx;
		background: #FFFFFF;
		padding: 30rpx 0;
		bottom: 0;
		left: 0;
		width: 100%;
		text-align: center;
		box-shadow: 0px 0 4rpx 1rpx rgba(0, 0, 0, 0.16);
		z-index: 999;
	}
</style>